<template>
  <el-card class="calendar-container">
    <el-calendar v-model="currentDate">
      <template #dateCell="{ data }">
        <div class="custom-cell">
          <!-- 显示日期（去掉年份） -->
          <div class="date-label">
            {{ formatCalendarDate(data.day) }}
          </div>

          <!-- 根据数据渲染滑块 -->
          <div v-if="getDateData(data.day)" class="slider-container">
            <el-slider
              v-model="getDateData(data.day).targetAmount"
              :min="0"
              :max="1000"
              :step="10"
              show-input
              input-size="mini"
              @change="handleAmountChange(data.day)"
            >
              <template #suffix>
                <span class="unit-suffix">元</span>
              </template>
            </el-slider>
          </div>

          <!-- 无数据提示 -->
          <div v-else class="no-data">暂无数据</div>
        </div>
      </template>
    </el-calendar>
  </el-card>
</template>

<script>
export default {
  props: {
    // 数据源格式验证
    sourceData: {
      type: Array,
      required: true,
      validator: (arr) =>
        arr.every(
          (item) =>
            item.dataDate &&
            typeof item.targetAmount === "number" &&
            /^\d{4}-\d{2}-\d{2}$/.test(item.dataDate)
        ),
    },
  },
  data() {
    return {
      currentDate: new Date(), // 当前显示月份
    };
  },
  computed: {
    // 将数组转换为日期映射表
    dateDataMap() {
      return this.sourceData.reduce((acc, cur) => {
        acc[cur.dataDate] = cur;
        return acc;
      }, {});
    },
  },
  methods: {
    // 日期格式化方法
    formatCalendarDate(fullDate) {
      return fullDate.split("-").slice(1).join("-");
    },

    // 获取对应日期的数据
    getDateData(dateString) {
      return this.dateDataMap[dateString] || null;
    },

    // 金额变更处理
    handleAmountChange(date) {
      const payload = {
        date,
        amount: this.dateDataMap[date].targetAmount,
      };
      this.$emit("data-change", payload);
    },
  },
};
</script>

<style scoped>
.calendar-container {
  margin: 20px;
  max-width: 1200px;
}

.custom-cell {
  height: 120px;
  padding: 5px;
  position: relative;
}

.date-label {
  font-size: 12px;
  font-weight: bold;
  color: #666;
  margin-bottom: 4px;
}

.slider-container {
  position: absolute;
  bottom: 5px;
  left: 0;
  right: 0;
  padding: 0 5px;
}

::v-deep .el-slider__input {
  width: 80px !important;
}

.unit-suffix {
  font-size: 12px;
  color: #999;
  margin-left: 4px;
}

.no-data {
  position: absolute;
  bottom: 15px;
  width: 100%;
  text-align: center;
  color: #ccc;
  font-size: 12px;
}

/* 调整日历单元格高度 */
::v-deep .el-calendar-table td {
  height: 130px;
  padding: 0 !important;
}

/* 当前日期的特殊样式 */
::v-deep .el-calendar-table td.is-selected {
  background-color: #f5f7fa;
}
</style>